<?php
namespace core;
use core\Util;
class ParamFilter{
	public $sort;
	public $order = 'asc';
	public $pageSize = 10;
	public $page = 1;
	public $grid;
	//使用的条件集合
	private $useParams = array();
	//所有的参数
	private $allParams = array();
	
	function __construct($params=null){
		if($params){
			$this->allParams = $params;
			//自动设置排序
			if(!empty($params["sort"])){
				$this->setOrder($params["sort"],$params["order"]);
			}
			//自动设置页数
			if(!empty($params["page"])){
				$this->page = (int)($params["page"]);
			}
			//自动设置分页大小
			if(!empty($params["rows"])){
				$this->pageSize = (int)($params["rows"]);
			}
			
			foreach($params as $name=>$val){
				if(Util::startWith($name,"Q_")){
					$this->addFilter($name,$val);
				}
			}
		}
	}
	
	//设置排序
	function setOrder($field,$direct){
		$this->sort = $field;
		$this->order = $direct;
	}
	
	function where($table){
		foreach($this->useParams as $key=>$r){
			switch(strtolower($r['sybol'])){
				case '=':
				case '<>':
				case '<':
				case '>':
				case '<=':
				case '>=':
					$table->where($r['field'],$r['sybol'],$r['value']);
					break;
				case 'like':
					$table->where($r['field'],'like','%'.$r['value'].'%');
					break;
				case 'llike':
					$table->where($r['field'],'like','%'.$r['value']);
					break;	
				case 'rlike':
					$table->where($r['field'],'like',$r['value'].'%');
					break;	
				case 'in':
					$valArr = explode(",",$r['value']);
					$table->whereIn($r['field'],$valArr);
					break;	
				case 'notin':
					$valArr = explode(",",$r['value']);
					$table->whereNotIn($r['field'],$valArr);
					break;
				case 'null':
					$table->whereNull($r['field']);
					break;
				case 'notnull':
					$table->whereNotNull($r['field']);
					break;		
			}
		}
	}
	
	/**
	 *	$name的值：Q_fieldName_[=、<>、<、>、<=、>=、
	 *  in、notin、like、llike,rlike、null、notnull]
	 *  $value 改字段的值
	 */
	function addFilter($name,$val=null){
		$arr = explode("_",$name);
		if(count($arr)<3) return;
		array_shift($arr); //移除Q
		$sybol = array_pop($arr); //移除符号
		$field = implode('_',$arr);  // 剩下为字段
		$field = str_replace('->','.',$field);
		$this->useParams[$name] = array(
			'field'=>$field,
			'value'=>$val,
			'sybol'=>$sybol
		);
	}
}